package com.gaogzhen.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaogzhen.domain.SysPrivilege;
import com.gaogzhen.service.SysPrivilegeService;
import com.gaogzhen.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 权限管理控制器
 * 1.查询
 *  1.1.分页查询
 * 2.新增
 * 3.修改
 * 4.删除
 * 权限管理的权限：
 * 1.查询: sys_privilege_query
 * 2.新增: sys_privilege_create
 * 3.修改: sys_privilege_update
 * 4.删除: sys_privilege_delete
 */
@RestController
@RequestMapping("/privileges")
@Api(tags = "权限管理")
public class SysPrivilegeController {

    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    /**
     * 分页查询权限
     * @param page
     * @return
     */
    @GetMapping
    @ApiOperation("分页查询权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小")
    })
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    public R<Page<SysPrivilege>> findByPage(@ApiIgnore Page<SysPrivilege> page) {
        // 最新数据优先显示->修改时间逆序排序：lastUpdateTime
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> sysPrivilegePage = sysPrivilegeService.page(page);
        return R.ok(sysPrivilegePage);
    }

    /**
     * 新增权限
     * @param sysPrivilege
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "sysPrivilege的json数据")
    })
    @PreAuthorize("hasAuthority('sys_privilege_create')")
    public R add(@RequestBody @Validated SysPrivilege sysPrivilege) {
        // 信息补全：创建人-mybatisplus自动填充功能补全
        boolean save = sysPrivilegeService.save(sysPrivilege);
        if (save) {
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 修改权限
     * @param sysPrivilege
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysPrivilege", value = "sysPrivilege的json数据")
    })
    @PreAuthorize("hasAuthority('sys_privilege_update')")
    public R update(@RequestBody @Validated SysPrivilege sysPrivilege) {
        // 信息补全：修改人-mybatisplus自动填充功能补全
        boolean update = sysPrivilegeService.updateById(sysPrivilege);
        if (update) {
            return R.ok();
        }
        return R.fail();
    }
}
